/** @format */

import classnames from 'classnames'
import { NavBar, SearchBar } from 'antd-mobile'

import SvgIcon from '@/components/SvgIcon/SvgIcon'
import styles from './Search.module.scss'
import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react'
import { getSuggListApi } from '@/api/search'

type SuggItem = {
  left: string
  search: string
  right: string
  text: string
}
const HISTORY_KEY = 'm-toutiao-history'
const Search = () => {
  const navigate = useNavigate()
  // 搜索文本框关键字
  const [keyword, setKeyword] = useState('')

  // 联想建议列表
  const [suggList, setSuggList] = useState<SuggItem[]>([])

  const [history, setHistory] = useState<string[]>(
    JSON.parse(localStorage.getItem(HISTORY_KEY) ?? '[]') as string[]
  )

  // 定时器idRef
  const timerRef = useRef(0)
  // 搜索框改变时
  const onKeywordChange = (text: string) => {
    setKeyword(text)
    if (timerRef.current) {
      clearTimeout(timerRef.current)
    }
    timerRef.current = window.setTimeout(async () => {
      if (!!keyword.replace(/\s+/g, '')) {
        setSuggList([])
        return
      }
      // 请求
      const {
        data: {
          data: { options }
        }
      } = await getSuggListApi(text)
      // 赋值
      setSuggList(highlight(options, text))
    }, 500)
  }
  // 关键字高亮
  function highlight(suggList: string[], keyword: string) {
    const regexp = new RegExp(keyword, 'i')
    const newSuggList = suggList
      .filter((item) => !Object.is(item, null))
      .map((item) => {
        const idx = item.search(regexp)
        const left = item.slice(0, idx)
        const search = item.slice(idx, idx + keyword.length)
        const right = item.slice(idx + keyword.length)
        return {
          left,
          search,
          right,
          text: item
        }
      })
    return newSuggList
  }

  // 搜索
  const onSearch = (text: string) => {
    if (!text.trim()) return
    navigate(`/search/${text}`)
    let newHistory = null
    if (history.includes(text)) {
      // 已存在
      newHistory = [text, ...history.filter((item) => item !== text)]
    } else {
      // 不存在
      newHistory = [text, ...history]
    }
    // 重新赋值
    setHistory(newHistory)
    // 存储到本地
    localStorage.setItem(HISTORY_KEY, JSON.stringify(newHistory))
  }

  // 删除
  const onDel = (idx: number) => {
    history.splice(idx, 1)
    setHistory([...history])
    localStorage.setItem(HISTORY_KEY, JSON.stringify(history))
  }
  // 清空
  const onClear = () => {
    setHistory([])
    localStorage.removeItem(HISTORY_KEY)
  }

  return (
    <div className={styles.root}>
      <NavBar
        className='navbar'
        onBack={() => navigate(-1)}
        right={
          <span
            className='search-text'
            onClick={() => onSearch(keyword)}>
            搜索
          </span>
        }>
        <SearchBar
          placeholder='请输入关键字搜索'
          value={keyword}
          onChange={onKeywordChange}
        />
      </NavBar>

      {/* 历史记录 */}
      {!keyword && (
        <div
          className='history'
          style={{
            display: history.length === 0 ? 'none' : 'block'
          }}>
          <div className='history-header'>
            <span>搜索历史</span>
            <span onClick={onClear}>
              <SvgIcon name='btn_del' />
              清除全部
            </span>
          </div>

          <div className='history-list'>
            {history.map((item, idx) => (
              <span
                className='history-item'
                key={idx}>
                <span
                  className='text-overflow'
                  onClick={() => onSearch(item)}>
                  {item}
                </span>
                <SvgIcon
                  name='btn_essay_close'
                  onClick={() => onDel(idx)}
                />
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 联想建议 */}
      <div className={classnames('search-result', !!keyword ? 'show' : '')}>
        {suggList.map((item, idx) => (
          <div
            className='result-item'
            key={idx}
            onClick={() => onSearch(item.text)}>
            <SvgIcon
              className='icon-search'
              name='btn_search'
            />
            <div className='result-value text-overflow'>
              {item.left}
              <span>{item.search}</span>
              {item.right}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default Search
